import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';

AudioPlayer _audioPlayer;

//单例方法——永远返回同一个实例
AudioPlayer getPlay() {
  if (_audioPlayer == null) {
    _audioPlayer = AudioPlayer();
  }
  return _audioPlayer;
}

// 为了让播放页面的时间进度条是否播放回到页面时还是到对应的位置
// 所以要做全局的===我看来就是做持久化

class PlayState extends InheritedWidget {
  final bool playing; //是否播放
  final int current; //当前播放进度
  final int total; //总进度
  final AudioPlayer player; //播放实例

  PlayState(
      {Key key,
      Widget child,
      this.playing,
      this.current,
      this.total,
      this.player})
      : super(key: key, child: child);

  static PlayState of(BuildContext context) {
    return context.dependOnInheritedWidgetOfExactType<PlayState>();
  }

  @override
  bool updateShouldNotify(PlayState oldWidget) {
    //true -> 应该更新 -> 不一样
    return oldWidget.playing != player ||
        oldWidget.current != current ||
        oldWidget.total != total;
  }

  @override
  String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) {
    return '''
playing: $playing
current: $current
total: $total
''';
  }
}

class PlayStateProvider extends StatefulWidget {
  final Widget child;
  PlayStateProvider({Key key, this.child}) : super(key: key);

  @override
  _PlayStateProviderState createState() =>
      _PlayStateProviderState(child: child);
}

class _PlayStateProviderState extends State<PlayStateProvider> {
  final Widget child;
  AudioPlayer player; //播放实例

  bool playing = false; //是否播放
  int current = 0; //当前播放进度
  int total = 0; //总进度

  _PlayStateProviderState({this.child}) : super() {
    player = getPlay();
    // 是否播放赋值
    player.onPlayerStateChanged.listen((event) {
      setState(() {
        playing = event == PlayerState.PLAYING;
      });
    });
    // 当前进度
    player.onAudioPositionChanged.listen((event) {
      setState(() {
        // print('current: ${event.inSeconds}');
        current = event.inSeconds;
      });
    });
    // 总进度赋值
    player.onDurationChanged.listen((event) {
      setState(() {
        // print('total: ${event.inSeconds}');
        total = event.inSeconds;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return PlayState(
      playing: playing,
      current: current,
      total: total,
      player: player,
      child: child,
    );
  }
}
